import plugin from '../../../lib/plugins/plugin.js';
import { loadConfig, saveConfig } from '../modules/imag.js';
import { parseSourceImg, uploadImage } from '../modules/image.js';
import { createLogger } from '../modules/Logger.js'; 

export class LinkPlugin extends plugin {
    constructor() {
        super({
            name: '皮皮直链',
            dsc: '图片直链获取工具',
            event: 'message',
            priority: 1000,
            rule: [
                {
                    reg: '^#直链',
                    fnc: 'zhil',
                },
                {
                    reg: '^#设置直链域名',
                    fnc: 'setDomain',
                    permission: 'master',
                },
                {
                    reg: '^#删除直链',
                    fnc: 'deleteLink',
                },
            ],
        });
        // 创建日志实例
        this.logger = createLogger(this.name);
    }


    async zhil(e) {
        this.logger.info(`收到命令: ${e.msg}`); // 记录命令

        // 使用 imageHandler.js 的 parseSourceImg 函数解析图片链接
        await parseSourceImg(e);

        if (!e.img || e.img.length === 0) {
            await this.reply('❌未找到有效的图片链接。');
            return true;
        }

        const imgUrl = e.img[0];
        this.logger.info(`匹配到的图片链接: ${imgUrl}`);

        // 获取并检查配置中的直链域名
        const config = loadConfig();
        const domain = config.link_domain;
        if (!domain) {
            await this.reply('请先使用 #设置直链域名 设置图片服务器域名');
            return true;
        }

        // 使用直链域名上传图片
        try {
            const uploadedUrl = await uploadImage(imgUrl, domain);
            await this.reply(uploadedUrl);
            this.logger.info(`上传成功，直链：${uploadedUrl}`);
        } catch (err) {
            this.logger.error(`上传失败: ${err.message}`);  
            await this.reply('上传失败：' + err.message);
        }

        return true;
    }


    async setDomain(e) {
        let domain = e.msg.replace(/^#设置直链域名/, '').trim();
        if (!domain) {
            await e.reply('请输入要设置的域名');
            return false;
        }

        // 移除末尾的斜杠
        domain = domain.replace(/\/$/, '');

        // 读取当前配置并保存直链域名
        const config = loadConfig();
        config.link_domain = domain;
        saveConfig(config);

        await e.reply(`直链域名已设置为：${domain}`);
        this.logger.info(`直链域名已设置为：${domain}`);

        return true;
    }

    async deleteLink(e) {
        this.logger.info(`收到删除命令: ${e.msg}`);

        const config = loadConfig();
        const domain = config.link_domain;
        if (!domain) {
            await e.reply('❌未设置有效的直链域名。');
            return true;
        }

        const cleanDomain = domain.replace(/^https?:\/\//, '');
        const linkMatch = e.msg.match(new RegExp(`https?://${cleanDomain.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/img/(.+\\.jpg)`));
        
        if (!linkMatch) {
            await e.reply('❌未找到有效的图片链接。', true);
            return true;
        }

        const filename = linkMatch[1];
        this.logger.info(`匹配到的文件名: ${filename}`);

        try {
            // 添加超时控制
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), 30000);

            const deleteResponse = await fetch(`${domain}/delete.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ filename }),
                signal: controller.signal,
            });
            clearTimeout(timeout);

            if (!deleteResponse.ok) {
                throw new Error(`删除请求失败: ${deleteResponse.status} ${deleteResponse.statusText}`);
            }

            const deleteResult = await deleteResponse.json();
            if (deleteResult.code !== 200) {
                await e.reply(`失败：${deleteResult.msg}`, true);
            } else {
                await e.reply('ok', true);
                this.logger.info(`删除成功：${filename}`);
            }
        } catch (err) {
            this.logger.error(`删除失败: ${err.message}`); 
            if (err.name === 'AbortError') {
                await e.reply('请求超时，请稍后重试', true);
            } else {
                await e.reply('删除失败：' + err.message, true);
            }
        }

        return true;
    }
}